<template>
	<view class="container">
		<custom-status-bar></custom-status-bar>
		<!-- 顶部导航 -->


		<uv-loading-page :loading="showLoading" loading-mode="spinner"></uv-loading-page>

		<view class="header">
			<view class="back-icon" @click="goBack">
				<uni-icons type="left" size="20" color="#1890ff"></uni-icons>
				<text>返回</text>
			</view>
			<text class="title">编辑地址</text>
		</view>
		<!-- 表单区域 -->
		<uv-form ref="formRef" :model="formData" :rules="rules">
			<uv-form-item label="姓名" prop="name" borderBottom class="first">
				<uv-input v-model="formData.name" placeholder="姓名" border="none" />
			</uv-form-item>
			<uv-form-item label="电话" prop="tel" borderBottom>
				<uv-input v-model="formData.tel" placeholder="电话" type="number" border="none" />
			</uv-form-item>
			<uv-form-item label="地区" prop="regionCheck" borderBottom>
				<uv-input v-model="regions" readonly placeholder="地区" @click="showRegionPicker" border="none" />
				<template #right>
					<uni-icons type="right" size="20" color="#666" />
				</template>
			</uv-form-item>
			<uv-form-item label="详细地址" labelWidth="100" prop="addressDetail" borderBottom class="detail-address">
				<uv-textarea v-model="formData.addressDetail" :maxlength="-1" autoHeight placeholder="详细地址"
					border="none"></uv-textarea>
			</uv-form-item>
			<uv-form-item label="邮政编码" labelWidth="100" prop="postalCode" :borderBottom="false" class="last">
				<uv-input v-model="formData.postalCode" placeholder="邮政编码" type="number" border="none" />
			</uv-form-item>
			<uv-form-item label="设为默认收货地址" labelPosition="left" labelWidth="150" prop="isDefault" class="default">
				<uv-switch v-model="formData.isDefault" :inactive-value="0" :active-value="1" activeColor="#232773" />
			</uv-form-item>
		</uv-form>
		<!-- 保存按钮 -->
		<button class="save-btn" @click="saveAddress">保存</button>
		<button class="delete-btn" @click="removeAddress">删除</button>
		<uv-picker ref="picker" :columns="addressList" :loading="loading" keyName="name" @change="change"
			@confirm="confirm">
		</uv-picker>
	</view>
</template>
<script setup>
import {
	ref,
	computed,
	reactive,
	nextTick,
	onMounted
} from 'vue';
import CustomStatusBar from '../../components/common/CustomStatusBar.vue';
import { onLoad } from "@dcloudio/uni-app"
import {
	findAddress,
	editAddress,
	deleteAddress
} from "@/api/index.js"

const showLoading = ref(true)



// 表单引用
const formRef = ref(null);
// 表单数据
const formData = reactive({
	aid: '',
	name: '',
	tel: '',
	province: '',
	city: '',
	county: '',
	addressDetail: '',
	areaCode: '', //地区编号
	postalCode: '',
	isDefault: 0, //0 非默认 1 默认
	regionCheck: ''
});
const picker = ref(null)
const loading = ref(true)
const region = reactive({
	provinces: [],
	citys: [],
	areas: [],
	pickerValue: [0, 0, 0],
	defaultValue: [3442, 1, 2] //默认是北京
})
const addressList = computed(() => {
	return [region.provinces, region.citys, region.areas]
})
// 地区
const regions = computed(() => {
	if (formData.province && formData.city && formData.county) {
		return formData.province + '/' + formData.city + '/' + formData.county
	}
	return ''
})
onLoad(async (options) => {
	const index = options.index
	if (uni.getStorageSync('coffee_token')) {

		showLoading.value = true
		// 查询当前地址信息
		const res = await findAddress(uni.getStorageSync('coffee_token'))
		if (res.code === 20000) {
			const address = res.result[index]
			formData.aid = address.aid
			formData.name = address.name
			formData.tel = address.tel
			formData.province = address.province
			formData.city = address.city
			formData.county = address.county
			formData.addressDetail = address.addressDetail
			formData.postalCode = address.postalCode
			formData.isDefault = address.isDefault

			// 设置验证字段
			if (formData.province && formData.city && formData.county) {
				formData.regionCheck = formData.province + formData.city + formData.county
			}

		}
	}
	await regionData()

	// 在获取到地址数据和区域数据后，更新picker的默认值
	handlePickValueDefault()

	showLoading.value = false
})
// 切换默认地址状态
const toggleDefault = (event) => {
	formData.value.isDefault = event.detail.value;
};
// 表单验证规则
const rules = {
	name: [{
		required: true,
		message: '请输入姓名',
		trigger: 'blur'
	}],
	tel: [{
		required: true,
		message: '请输入电话',
		trigger: 'blur'
	}, {
		pattern: /^1[3-9]\d{9}$/,
		message: '请输入正确的手机号',
		trigger: 'blur'
	}],
	regionCheck: [{
		required: true,
		message: '请选择地区',
		trigger: 'change'
	}],
	addressDetail: [{
		required: true,
		message: '请输入详细地址',
		trigger: 'blur'
	}],
	postalCode: [{
		pattern: /^\d{6}$/,
		message: '请输入正确的邮政编码',
		trigger: 'blur'
	}]
};

const regionData = () => {
	loading.value = true
	uni.request({
		method: 'GET',
		url: `/static/region.json`,
		success: res => {
			const {
				statusCode,
				data
			} = res
			if (statusCode === 200) {
				// console.log('获取的数据：', res);
				region.provinces = data.sort((left, right) => (Number(left.code) > Number(right.code) ?
					1 : -1));
			}
		},

		complete: () => {
			loading.value = false
		}

	})

}
const handlePickValueDefault = () => {
	// 根据已有的省市区信息设置picker的默认值
	if (formData.province && formData.city && formData.county) {
		// 查找省的索引
		const provinceIndex = region.provinces.findIndex(item => item.name === formData.province);
		if (provinceIndex !== -1) {
			region.pickerValue[0] = provinceIndex;
			region.citys = region.provinces[provinceIndex]?.children || [];

			// 查找市的索引
			const cityIndex = region.citys.findIndex(item => item.name === formData.city);
			if (cityIndex !== -1) {
				region.pickerValue[1] = cityIndex;
				region.areas = region.citys[cityIndex]?.children || [];

				// 查找区的索引
				const areaIndex = region.areas.findIndex(item => item.name === formData.county);
				if (areaIndex !== -1) {
					region.pickerValue[2] = areaIndex;
				}
			}
		}

		// 设置picker的默认位置
		picker.value?.setIndexs([region.pickerValue[0], region.pickerValue[1], region.pickerValue[2]], true);

		console.log("当前regions：", regions)
	} else {
		// 如果没有地区信息，则使用默认值
		region.pickerValue[0] = region.provinces.findIndex(item => Number(item.id) === region.defaultValue[0]);
		region.citys = region.provinces[region.pickerValue[0]]?.children || [];
		region.pickerValue[1] = region.citys.findIndex(item => Number(item.id) === region.defaultValue[1]);
		region.areas = region.citys[region.pickerValue[1]]?.children || [];
		region.pickerValue[2] = region.areas.findIndex(item => Number(item.id) === region.defaultValue[2]);
		picker.value?.setIndexs([region.pickerValue[0], region.pickerValue[1], region.pickerValue[2]], true);
	}
}
// 显示地区选择器
const showRegionPicker = () => {
	// 实际开发中调用地区选择组件
	console.log('显示地区选择器');
	if (picker.value) {
		picker.value.open(); //　打开地区选择器
		handlePickValueDefault() //初始化数据
	}
};
const change = (e) => {
	// if (loading.value) return;
	console.log("e", e)
	const {
		columnIndex,
		index,
		indexs
	} = e
	// 改变了省
	if (columnIndex === 0) {
		region.citys = region.provinces[index]?.children || []
		region.areas = region.citys[0]?.children || []
		picker.value.setIndexs([index, 0, 0], true)
	} else if (columnIndex === 1) {
		region.areas = region.citys[index]?.children || []
		picker.value.setIndexs(indexs, true)
	}
}
const confirm = (e) => {
	console.log('确认选择的地区：', e);
	const {
		indexs,
		value,
		values
	} = e
	// 最终选中的值
	//省
	formData.province = value[0].name
	// 市
	formData.city = value[1].name
	// 区
	formData.county = value[2].name
	// 地区编号
	formData.areaCode = value[2].code
	// 设置验证字段，当选择了完整地区信息时，设置为非空值
	if (formData.province && formData.city && formData.county) {
		formData.regionCheck = formData.province + formData.city + formData.county
	}
	// uni.showToast({
	// 	icon: 'none',
	// 	title: `${e.value[0].name}/${e.value[1].name}/${e.value[2].name}`
	// })
}
// 保存地址
const saveAddress = async () => {
	try {
		// 先进行表单验证
		await formRef.value.validate()
		console.log('需要保存的地址数据:', formData);

		// 调用保存地址接口
		if (uni.getStorageSync('coffee_token')) {
			const res = await editAddress(
				uni.getStorageSync('coffee_token'),
				formData.aid,
				formData.name,
				formData.tel,
				formData.province,
				formData.city,
				formData.county,
				formData.addressDetail,
				formData.areaCode,
				formData.postalCode,
				formData.isDefault
			)

			console.log("editAddress response", res)

			if (res.code === 9000) {
				uni.showToast({
					title: res.msg,
					icon: 'success'
				});
			}
		}

	} catch (errors) {
		console.log('表单验证失败或保存失败:', errors);
		uni.showToast({
			title: '请检查输入信息',
			icon: 'none'
		});
	}
};

// 删除地址
const removeAddress = async () => {

	if (uni.getStorageSync('coffee_token')) {

		uni.showModal({
			title: '提示',
			content: '确定要删除这个地址吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						const result = await deleteAddress(
							uni.getStorageSync('coffee_token'),
							formData.aid
						)

                         // console.log("deleteAddress",result)
						if (result.code === 10000) {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
						}
					} catch (error) {
						console.log('删除失败:', error);
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						});
					}
				}
			},
			complete:()=>{
				const pages = getCurrentPages();
				if (pages.length > 1) uni.navigateBack();
			}
		});
	}

}

const goBack = () => {
	const pages = getCurrentPages();
	if (pages.length > 1) uni.navigateBack();
		else  uni.switchTab({ url: '/pages/index/index' });
}
</script>
<style scoped>
.container {
	position: relative;
	padding: 0 20rpx;
	background-color: #eee;
	height: 100vh;
}

.header {
	position: relative;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100rpx;
	border-bottom: 1rpx solid #eee;
}

.back-icon {
	position: absolute;
	left: 0;
	top: 50%;
	transform: translateY(-50%);
	display: flex;
	align-items: center;
	font-size: 28rpx;
}

.title {
	font-size: 36rpx;
	font-weight: bold;
}

.form {
	margin-top: 20rpx;
	/* background: white; */
	border-radius: 20rpx;
	padding: 20rpx;
}

.uv-form-item {
	background: white;
	padding: 10rpx 50rpx;
	padding-top: 0;
	padding-bottom: 0;
}

.first {
	border-top-right-radius: 20rpx;
	border-top-left-radius: 20rpx;
}

.last {
	border-bottom-right-radius: 20rpx;
	border-bottom-left-radius: 20rpx;
	border-bottom: none;
	padding-top: 0;
	padding-bottom: 0;
}

.uv-textarea {
	padding: 0;
}

.default {
	position: relative;
	margin-top: 30rpx;
	border-radius: 20rpx;
}

.uv-switch {
	position: absolute;
	right: 50rpx
}

.save-btn {
	background: #232773;
	color: white;
	border-radius: 60rpx;
	padding: 10rpx 20rpx;
	font-size: 32rpx;
	margin-top: 50rpx;
}

.delete-btn {
	background: white;
	color: #333;
	border-radius: 60rpx;
	padding: 10rpx 20rpx;
	font-size: 32rpx;
	margin-top: 20rpx;
}
</style>